package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type route struct {
}

func printReq(req *http.Request) {
	fmt.Println("Method", req.Method)
	fmt.Println("URL", req.URL)
	fmt.Println("Proto", req.Proto)
	fmt.Println("ProtoMajor", req.ProtoMajor)
	fmt.Println("ProtoMinor", req.ProtoMinor)
	fmt.Println("Header", req.Header)
	fmt.Println("Body", req.Body)
	fmt.Println("ContentLength", req.ContentLength)
	fmt.Println("TransferEncoding", req.TransferEncoding)
	fmt.Println("Close", req.Close)
	fmt.Println("Host", req.Host)
	fmt.Println("Form", req.Form)
	fmt.Println("PostForm", req.ParseForm)
	fmt.Println("MultipartForm", req.MultipartForm)
	fmt.Println("Trailer", req.Trailer)
	fmt.Println("RemoteAddr", req.RemoteAddr)
	fmt.Println("RequestURI", req.RequestURI)
	fmt.Println("TLS", req.TLS)
	fmt.Println("Cancel", req.Cancel)
	fmt.Println("Response", req.Response)
	fmt.Println("--------------------------------------------------------------")
}
func printRes(res *http.Response) {
	fmt.Println("Status", res.Status)
	fmt.Println("StatusCode", res.StatusCode)
	fmt.Println("Proto", res.Proto)
	fmt.Println("ProtoMajor", res.ProtoMajor)
	fmt.Println("ProtoMinor", res.ProtoMinor)
	fmt.Println("Header", res.Header)
	fmt.Println("Body", res.Body)
	fmt.Println("ContentLength", res.ContentLength)
	fmt.Println("TransferEncoding", res.TransferEncoding)
	fmt.Println("Close", res.Close)
	fmt.Println("Uncompressed", res.Uncompressed)
	fmt.Println("Trailer", res.Trailer)
	fmt.Println("Request", res.Request)
	fmt.Println("TLS", res.TLS)
	fmt.Println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
}
func (r route) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	//req.URL.Host = "https://vjude.net"
	printReq(req)
	path := "https://vjudge.net"
	originDomain := "Domain=.vjudge.net;"
	//domain := "Domain=.vjudge.gzhuacm.cn;"
	domain := ""
	//u, err := url.Parse("https://vjudge.net")
	u, err := url.Parse(path + req.RequestURI)
	if err != nil {
		fmt.Println(err)
		return
	}
	//fmt.Println("url:", u.RawPath, u.Host, u.RawQuery)
	client0 := &http.Client{}
	req1, err := http.NewRequest("GET", "http://172.22.27.1", nil)
	printReq(req1)
	req.URL = u
	req.RequestURI = ""
	req.Host = u.Host
	printReq(req)
	//req1, err := http.NewRequest(req.Method, path+req.RequestURI, req.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	resp, err := client0.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	printRes(resp)
	defer resp.Body.Close()

	for k, v := range resp.Header {
		for _, vv := range v {
			if strings.Count(vv, originDomain) != 0 {
				vv = strings.Replace(vv, originDomain, domain, -1)
			}
			w.Header().Add(k, vv)
		}
	}
	fmt.Println(w.Header(), "\n----------------------\n")

	w.WriteHeader(resp.StatusCode)
	result, err := ioutil.ReadAll(resp.Body)
	if err != nil && err != io.EOF {
		panic(err)
	}
	w.Write(result)
}
func main() {
	r := &route{}
	http.ListenAndServe(":8002", r)
}
